#-*-coding:utf-8 -*-
import urllib2,urllib,re,sys
#server's url
post_target="http://jules.unavco.org/Geoid/Geoid"
#format input data
#output:(degree,minus,second) in str format
def standardize(data):
    _deg=_min=_sec=0
    if re.match(r"[+-]?\d*:\d*:\d*\.?\d*",data):
        _deg,_min,_sec=data.split(":")
    elif re.match(r"[+-]?\d*\.?\d*",data):
        _data=1 if float(data)>0 else -1
        data=abs(float(data))
        _deg=int(data)
        data=(data-_deg)*60
        _min=int(data)
        _sec=str((data-_min)*60)
        _min=str(_min)
        _deg*=_data
    return (_deg,_min,_sec)
#output:(lat,lng,wgs84_height,Geoid_height,Orthometric_height)
def get(lat,lng,alt):
    try:
        parse_lat=standardize(lat)
        parse_lng=standardize(lng)
        post_data={"lat":parse_lat[0],"lat_m":parse_lat[1],"lat_s":parse_lat[2],"lon":parse_lng[0],"lon_m":parse_lng[1],"lon_s":parse_lng[2],"gpsheight":alt}
        rlt=urllib2.urlopen(post_target,urllib.urlencode(post_data)).read()
        rlt_arr=re.findall(r"=\s*([+-]?(\d*)?(\.\d*)?)",rlt)
        return (rlt_arr[0][0],rlt_arr[2][0],rlt_arr[4][0],rlt_arr[5][0],rlt_arr[6][0])
    except:
        print "[Warn]Maybe wrong format"
def usage():
    print """
Use:egm96-get.py lat,lng,alt
Result:(lat,lng,wgs84_height,Geoid_height,Orthometric_height)
What:get the geoid height and orthometric height(height above EGM96 geoid which approximates mean sea leve)with given latitude,longitude,height from website called unavco.org
Example1:egm96-get.py 34.3232,125.4343,124
Example2:egm96-get.py 23:32:12.222,125:44:2,100
    """
if __name__=="__main__":
    if len(sys.argv)==1:
        usage()
    else:
        print "\t".join( get(*sys.argv[1].split(",")))